package server.handler;

import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author srh
 * @date 2020/10/18
 **/
public class AcceptHandlerAbstract extends AbstractSelectionKeyHandler {

    @Override
    public boolean preHandler(SelectionKey selectionKey) {
        return selectionKey.isAcceptable();
    }

    @Override
    public void handler(SelectionKey selectionKey) {
        try {
            // 获取到init方法中注册到 selector 中的 serverSocketChannel
            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
            // 阻塞方法，客户端发起后阻塞返回
            SocketChannel channel = serverSocketChannel.accept();
            // channel 设置为非阻塞
            channel.configureBlocking(false);
            // 设置对应的客户端通道标记，设置此通道为可读时使用
            channel.register(this.selector, SelectionKey.OP_READ);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
